package public

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"strings"
)

type WxAccessTokenResponse struct {
	ErrCode     int    `json:"errcode"`
	ErrMsg      string `json:"errmsg"`
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}
type WxSentMessageResponse struct {
	ErrCode int    `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
}

const wxAccessKey = "wxAccessKey"
const wxTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"

type WxMessageReservation struct {
	ToUer       string                            `json:"touser" comment:"接受者openId"`
	TemplateId  string                            `json:"template_id" comment:"模板id"`
	Url         string                            `json:"url" comment:"模板跳转链接"`
	MiniProgram map[string]interface{}            `json:"miniprogram"`
	Data        map[string]map[string]interface{} `json:"data" comment:"模板数据"`
	AppId       string                            `json:"app_id"`
	Secret      string                            `json:"secret"`
}

func (w *WxMessageReservation) Send() error {
	fmt.Println(w.MiniProgram)
	body, err := json.Marshal(w)
	if err != nil {
		return err
	}
	reqBody := strings.NewReader(string(body))
	accessToken, err := w.GetAccessToken()
	if err != nil {
		return err
	}
	resp, err := http.Post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken, "application/json;charset=utf-8", reqBody)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	wxResp := WxSentMessageResponse{}
	decoder := json.NewDecoder(resp.Body)
	if err := decoder.Decode(&wxResp); err != nil {
		return err
	}
	fmt.Println(wxResp.ErrMsg, wxResp.ErrCode)
	return nil
}
func (w *WxMessageReservation) GetAccessToken() (string, error) {
	accessToken, err := GetStore(wxAccessKey)
	if err != nil {
		//需要重新获取accessToken
		resp, err := http.Get(fmt.Sprintf(wxTokenUrl, w.AppId, w.Secret))
		if err != nil {
			return "", err
		}
		defer resp.Body.Close()
		wxResp := WxAccessTokenResponse{}
		decoder := json.NewDecoder(resp.Body)
		if err := decoder.Decode(&wxResp); err != nil {
			return "", err
		}
		if wxResp.ErrCode != 0 {
			return "", errors.New(wxResp.ErrMsg)
		}
		SetStore(wxAccessKey, wxResp.AccessToken, wxResp.ExpiresIn-10)
		return wxResp.AccessToken, nil
	}
	return accessToken, nil
}
